<template>
  <div v-show="$route.name == 'task-save'">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/user-list' }" v-if="showUser">用户列表</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/task-list' }">任务管理记录</el-breadcrumb-item>
      <el-breadcrumb-item>新增任务</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <div class="title-name">新增任务</div>
      <el-form :model="task" :rules="rules" ref="task" label-width="120px" class="demo-saveForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="项目" prop="project_id">
              <el-select v-model="task.project_id" popper-class="dropdownbox" class="form-item" placeholder="请选择项目" >
                <el-option v-for="item in projectList" :label="item.project_name"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.project_name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务名称" prop="task_name">
              <el-input v-model="task.task_name" placeholder="请输入任务名称" class="form-item"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人" prop="task_user_id">
              <el-select v-model="task.task_user_id" popper-class="dropdownbox" class="form-item" placeholder="请选择负责人">
                <el-option v-for="item in userList" :label="item.truename"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.truename }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="预计完成时间" prop="estimated_date">
              <el-date-picker type="date" placeholder="选择日期" v-model="task.estimated_date" class="form-item"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务描述" prop="desc">
              <el-input type="textarea" v-model="task.desc" class="form-item"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否需要检查" prop="is_check">
              <el-radio-group v-model="task.is_check">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="文件：" prop="fileList" >
              <el-upload
                action="https://if.prowealthgroup.cn/task-produce/public/index.php/task-upload"
                list-type="picture-card"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :on-error="handleError"
                :before-remove="beforeRemove"
                :file-list="task.fileList">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" @click="handleSubmit">提交</el-button>
            <el-button  @click="back" style="margin-left: 5px">返回</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      userId: '',
      task: {
        project_id: '',
        task_name: '',
        task_user_id: '',
        estimated_date: '',
        is_check: 1,
        fileList: [],
        desc: ''
      },
      rules: {
        project_id: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
        is_check: [{ required: true, message: '请选择是否检查', trigger: 'change' }],
        task_name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        task_user_id: [{ required: true, message: '请选择执行人', trigger: 'change' }],
        estimated_date: [{ required: true, message: '请选择日期', trigger: 'blur' }],
        desc: [{ required: true, message: '请填写任务描述', trigger: 'blur' }]
      },
      userList: [],
      projectList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      departmentId: [],
      showUser: true
    }
  },
  watch: {
    'task.project_id': {
      handler: function(val, oldval) {
        if (val) {
          this.userList = []
          this.task.task_user_id = ''
          this.getDevUserList()
        } else {
          this.userList = []
          this.task.task_user_id = ''
        }
      }
    }
  },
  mounted() {
    this.getUserInfo()
  },
  created() {
    // 是否可以展示用户列表
    this.auths = JSON.parse(localStorage.task_auths)
    if (this.auths.indexOf('show-user') === -1) {
      this.showUser = false
    }
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      this.userId = localStorage.task_user
      const { data: result } = await this.$http.get('/user/' + this.userId)
      result.data.department.forEach(element => {
        this.departmentId.push(element.id)
      })
      this.getProject()
    },
    // 获取项目
    async getProject() {
      const params = {
        page: 1,
        pageSize: 100000,
        departmentId: this.departmentId
      }
      const { data: result } = await this.$http.get('/project', { params: params })
      if (result.status !== 200) {
        return this.$message.error(result.msg)
      }
      this.projectList = result.data
    },
    // 获取开发人员
    async getDevUserList() {
      const params = {
        page: 1,
        pageSize: 100000,
        project_id: this.task.project_id
      }
      const { data: result } = await this.$http.get('/user', { params: params })
      if (result.status !== 200) {
        return this.$message.error(result.msg)
      }
      result.data.forEach(item => {
        if (item.auths.indexOf("task-publish-able") !== -1) {
          this.userList.push(item) 
        }
      })
    },
    // 移除文件
    async handleRemove(file, fileList) {
      var url = file.response.data.downUrl
      await this.$http.post('/task-download-cancel', { url: url }, { type: 'json', responseType: 'blob' }).then(res => {
        if (res.status === 200) {
          this.task.fileList = fileList
          return this.$message.success('移除成功')
        }
        return this.$message.error(res.msg)
      }).catch(() => {
        return this.$message.error('移除失败')
      })
    },
    beforeRemove(file) {
      var msg = '确定移除' + file.name + '？'
      return this.$confirm(msg)
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 上传失败
    handleError(err, file) {
      this.$message.warning(err)
    },
    // 文件上传成功
    handleSuccess(res, file, fileList) {
      file.url = res.data.url
      this.task.fileList = fileList
      this.$message.success(res.msg)
    },
    // 下载指定目录文件
    // async download(url, name) {
    //   var downUrl = url.url ? url.url : url
    //   await this.$http.post('/task-download', {url: downUrl, name: name}, { type: 'json',responseType:'blob' }).then(res => {
    //     if (res.status === 200) {
    //       const fileName = decodeURI(
    //         res.headers["content-disposition"].split("=")[1]
    //       )
    //       const blob = res.data
    //       const reader = new FileReader()
    //       reader.readAsDataURL(blob)
    //       reader.onload = (e) => {
    //         const a = document.createElement('a')
    //         a.download = fileName
    //         a.href = e.target.result
    //         a.click()
    //       }
    //       return this.$message.success('导出成功')
    //     }
    //     return this.$message.error(res.msg)
    //   }).catch (() => {
    //     return this.$message.error('导出失败')
    //   })
    // },
    // 提交
    async handleSubmit() {
      this.$refs.task.validate(async (valid) => {
        const taskList = this.task.fileList.map(item => {
          return {
            url: item.url,
            name: item.name
          }
        })
        const date = new Date(this.task.estimated_date)
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var day = date.getDate()
        if (!valid) return
        let data = {
          project_id: this.task.project_id,
          task_name: this.task.task_name,
          assign_user_id: this.userId,
          task_user_id: this.task.task_user_id,
          is_check: this.task.is_check,
          estimated_date: `${year}-${month}-${day}`,
          file_url: taskList,
          desc: this.task.desc
        }
        // 可以发起新增入库单的网络请求
        const { data: result } = await this.$http.post('/task', data)
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
        this.$message.success('保存成功！')
        this.$router.push({ path: '/task-list' })
      })
    },
    // 返回
    back () {
      this.$router.push({ 'name': 'task-list' })
    }
  }
}
</script>
<style lang="less" scoped>
.title-name {
  margin-bottom: 20px;
}
.form-item {
  width:300px
}
.upload-demo {
  width: 300px;
}
</style>
